package card

import (
	"context"
	"strings"

	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/forum/model"
	"mall/service/forum/rpc/internal/svc"
	"mall/service/forum/rpc/internal/utils"
	"mall/service/forum/rpc/internal/utils/errorhandler"
	"mall/service/forum/rpc/types/forum"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetCardListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetCardListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetCardListLogic {
	return &GetCardListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// ##25.04.10##
func (l *GetCardListLogic) GetCardList(in *forum.CardListReq) (*forum.CardListResp, error) {
	if in.Filter == nil || len(*in.Filter) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	preloadMap, _ := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)

	forumCardEntityName := model.RpcEntityNames.ForumCard
	if _, ok := model.RpcEntityPreloadMap[forumCardEntityName]; !ok {
		return &forum.CardListResp{}, nil
	}

	forumCardRepositoryName := model.RepositoryNames.ForumCard
	columnMap, ok := model.RepositoryPreloadMap[forumCardRepositoryName]
	if !ok {
		return &forum.CardListResp{}, nil
	}

	var selectCols []string
	if preloadFields, ok := preloadMap[forumCardEntityName]; ok {
		selectCols = modelx.ParseSelectColumns(preloadFields, columnMap)
	}

	filterMap := modelx.ParseFilter(in.Filter, columnMap)

	if filterMap == nil {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	orderBy := modelx.ParseSorter(in.Sorter, columnMap)
	if len(orderBy) == 0 {
		orderBy = model.ForumPostCardColumns.PostID + " DESC"
	}

	res, count, err := l.svcCtx.Post.GetCard(l.ctx, model.M{
		"offset":  in.Offset,
		"limit":   in.Limit,
		"orderBy": orderBy,
		"select":  strings.Join(selectCols, ","),
	}, -1, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	hasNextPage, hasPreviousPage := modelx.ParseCount(count)
	resp := &forum.CardListResp{
		HasNextPage:     &hasNextPage,
		HasPreviousPage: &hasPreviousPage,
	}
	if len(res) > 0 {
		for _, v := range res {
			cardType := utils.FormatCardType(int32(v.ObjectType))
			resp.List = append(resp.List, &forum.PostCardInfo{
				Uid:      pointy.GetPointer(v.ID),
				Id:       pointy.GetPointer(v.ObjectID),
				Type:     pointy.GetPointer(cardType),
				LinkUrl:  pointy.GetPointer(v.LinkURL),
				Title:    pointy.GetPointer(v.Title),
				PicUrl:   pointy.GetPointer(v.PicURL),
				Subtitle: pointy.GetPointer(v.Subtitle),
				Label:    pointy.GetPointer(v.Label),
				Price:    pointy.GetPointer(v.Price),
			})
		}
	}

	return resp, nil
}
